package controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.appengine.api.datastore.Text;

@SuppressWarnings("serial")
public class LookupIpServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
		resp.setHeader( "Cache-Control", "public, max-age=86400");
		resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		String ip = req.getParameter("ip");
		
		String Decimal = "-";
		String Hostname = "-";
		String ISP = "-";
		String Organization = "-";
		String Services = "-";
		String Type = "-";
		String Assignment = "-";
		String Country = "-";
		String Region = "-";
		String City = "-";
		String Latitude = "-";
		String Longitude = "-";
		
		String content = "";
		if(ip!=null)
			ip = ip.replaceAll("[^0-9.]+", "");
		if(ip!=null&&ip.length()>0&&Pattern.matches("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$", ip))
		{
			try {
				resp.setHeader( "Cache-Control", "public, max-age=86400");
				resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
				URL dataURL = new URL("http://whatismyipaddress.com/ip/"+ip);
				HttpURLConnection connection = (HttpURLConnection) dataURL.openConnection();
			    connection.setInstanceFollowRedirects(true);
			    connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.21) Gecko/20110830 AlexaToolbar/alxf-2.14 AlexaToolbar/pXVUnvuf-1.2 Firefox/3.6.21");
				connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
				connection.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
				connection.setRequestProperty("Accept-Charset", "	ISO-8859-1,utf-8;q=0.7,*;q=0.7");
				connection.setRequestProperty("Connection", "keep-alive");
				connection.setRequestProperty("Keep-Alive", "115");
				connection.setRequestProperty("Cookie", "PREF=ID=987bb7a56b1cc7bc:U=691fa246d56f502e:FF=0:TM=1314876638:LM=1314876681:S=yBXzqp_WQq9ykX-j; NID=50=nfNXg7ymSSsfdzMnkEuo7t1GCgIEwcK5xmpFhu1mQWwvNI5nFHLZpRsy_1XnaoKrdj9hnz7za9-M2OIO99phfFSTmXln-xCvqzJaRWHsN0EQKgpmkvgUDTWPVF4I4c9L; SID=DQAAALcAAADhqr-J8Ls3CKhmbRjwTMMP1DjmIvR8qBFxv99saTaFFgoRsVf18W4p_BTocYoxYNMvsvh9sfjMj7KqLyd_s9Y0lwYY_Rrljd7t5IpKBTWWnsv9VSJ_qelH943zV8YIT3uuIdJbHhFlCnVEu_YealZoldWjf4VirYR0PIrr0i4_JU2JCHRmpyW0ACt3KcyLkukJlGDyT5yC5js3CBSTAhnWSylBpMWPWyWJzqXe2BQFcdfuU_qo00pAR-uEcMQ437M; HSID=A9Z-j3CKhzDEykAES");
				connection.setRequestProperty("Cache-Control", "max-age=0");
				BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("utf-8")));
				
				char[] buf = new char[102102];
				int numRead=0;
		        while((numRead=reader.read(buf)) != -1){
		            String readData = String.valueOf(buf, 0, numRead);
		            content += readData;
		            buf = new char[102102];
		        }
		        reader.close();
				
				Document doc = Jsoup.parse(content);
				
				Decimal = doc.select("div[id=section_content]").select("table").get(0).select("td").get(1).text();
				Hostname = doc.select("div[id=section_content]").select("table").get(0).select("td").get(2).text();
				ISP = doc.select("div[id=section_content]").select("table").get(0).select("td").get(3).text();
				Organization = doc.select("div[id=section_content]").select("table").get(0).select("td").get(4).text();
				Services = doc.select("div[id=section_content]").select("table").get(0).select("td").get(5).text();
				Type = doc.select("div[id=section_content]").select("table").get(0).select("td").get(6).text();
				Assignment = doc.select("div[id=section_content]").select("table").get(0).select("td").get(7).text();
				Country = doc.select("div[id=section_content]").select("table").get(1).select("td").get(0).text();
				Region = doc.select("div[id=section_content]").select("table").get(1).select("td").get(1).text();
				City = doc.select("div[id=section_content]").select("table").get(1).select("td").get(2).text();
				Latitude = doc.select("div[id=section_content]").select("table").get(1).select("td").get(3).text();
				Longitude = doc.select("div[id=section_content]").select("table").get(1).select("td").get(4).text();

	
			} catch (Exception e) {
				
				e.printStackTrace();
			}
		}
		req.setAttribute("Decimal", Decimal);
		req.setAttribute("Hostname", Hostname);
		req.setAttribute("ISP", ISP);
		req.setAttribute("Organization", Organization);
		req.setAttribute("Services", Services);
		req.setAttribute("Type", Type);
		req.setAttribute("Assignment", Assignment);
		req.setAttribute("Country", Country);
		req.setAttribute("Region", Region);
		req.setAttribute("City", City);
		req.setAttribute("Latitude", Latitude);
		req.setAttribute("Longitude", Longitude);
		
		req.setAttribute("ip", ip);
		try {
			req.getRequestDispatcher("/lookup-ip.jsp").forward(req, resp);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
